/**
 * 开始尝试使用es6来写react
 * 其实不需要用{}包起来的
 * Created by levy on 16/5/30.
 */
import Radio from "../components/form/Radio";
import Select from "../components/form/Select";
import DatePicker from "../components/form/DatePicker";
import InputText from "../components/form/InputText";
import TextArea from "../components/form/TextArea";
import DetailInfo from "../components/detail/ImgTextDetail";
import LargeImgLayer from "../components/LargeImg";
import FooterBtn from "../components/detail/FooterBtn";
import BottomForm from "../components/detail/BottomForm";
import PersonSelect from "../components/detail/SelectPerson";
import {health} from "../const/offices";
import {prefix} from "../const/prefix";


{
    var lf = liefeng,
        api = lf.api,
        api = health.api,
        apiUrl = prefix.oldpeople,
        appAlert = lf.bridgeJs.alert,
        setTitle = lf.bridgeJs.setTitle,
        {log, ajax} = lf.utils,
        dataId,
        eventId = lf.utils.getUrlParam('eventId');


    var FormInfo = React.createClass({
        getInitialState() {
            return {
                location: '',
            }
        },
        componentWillMount() {
        },
        componentDidMount() {
            //log(this.refs.form.getDOMNode())
        },
        _onChange(e) {
            this.setState({location: e.target.value});
        },
        render() {
            var data = this.props.data,
                radios = [
                    {
                        text: '重要',
                        value: 1,
                        name: 'important',
                        active: data.important > 0
                    },
                    {
                        text: '紧急',
                        value: 1,
                        name: 'emergency',
                        active: data.emergency > 0
                    },
                    {
                        text: '有偿',
                        value: 1,
                        name: 'serviceType',
                        active: data.serviceType > 0
                    }
                ].map((data) => <Radio {...data}/>);

            return <form className="margin-top" ref="form">
                <div className="input-row">
                    <label>服务类型：</label>
                    <Select name="eventType" groupCode="EVENT_TYPE" addClass="arrow"/>
                </div>
                <div className="input-row">
                    <label>具体类别：</label>
                    <Select name="category" groupCode="EVENT_CATEGORY" addClass="arrow"/>
                </div>
                <div className="input-row">
                    <label>预约时间：</label>
                    <DatePicker {...{
                        value: lf.utils.format(data.orderTime), name: "appointmentTime",
                        addClass: "float-right"
                    }}/>
                </div>
                <div className="input-row">
                    <label>工作位置：</label>
                    <InputText name="location" value={data.location} addClass="float-right"/>
                </div>
                <div className="btn-box">
                    {radios}
                </div>
                <div className="margin-top"></div>
                <div className="container">
                    <div className="margin-bottom">内容描述：</div>
                    <TextArea name="content" value={data.content} placeholder="必填*"/>
                </div>
            </form>
        }
    });

    var Root = React.createClass({
        getInitialState() {
            return {
                imgSrc: '',
                largeImgVisible: '',
                formVisible: '',
                formConVisible: '',
                isFeedback: '',
                tableTitList: [
                    ['projectName', '所属项目'],
                    ['houseNum', ' 房 号 '],
                    ['proprietorName', ' 业 主 '],
                    ['reporterName', '报 事 人'],
                    ['reportTime', '报事时间'],
                    ['reportMode', '报事方式'],
                    ['phone', '联系方式']
                ],
                detailData: {},
            }
        },
        componentWillMount() {
            var me = this;
            ajax({
                url:apiUrl + api.detail,
                type: 'POST',
                data: {
                    eventId: eventId,
                },
                headers: {
                    openId: dataId.openId,
                },
                success:function(data){
                   me.setState({detailData: data.data});
                }
            })
        },
        render() {
            let footerBtn = [
                    {aLinkClass: 'green', clickHandler: this.showFeedback, text: '直接反馈'},
                    {aLinkClass: 'green ', clickHandler: this.showDispatch, text: '派单'},
                ],
                formFooterBtn = [
                    {aLinkClass: 'green', clickHandler: this.hideBottomForm, text: '取消'},
                    {aLinkClass: 'green ', clickHandler: this.submit, text: '提交'},
                ];

            return <div className="report-detail">
                <DetailInfo data={this.state.detailData}
                            tableTitList={this.state.tableTitList}
                            enlargeHandler={this._enlargeHandler}
                            title={this.props.title}/>
                <FormInfo data={this.state.detailData}/>
                <FooterBtn data={footerBtn}/>
                <BottomForm
                    itemRender={this.itemRender}
                    formFooterBtn={formFooterBtn}
                    formVisible={this.state.formVisible}
                    formConVisible={this.state.formConVisible}
                />
                <LargeImgLayer imgSrc={this.state.imgSrc}
                               hideHandler={this._hideHandler}
                               visible={this.state.largeImgVisible}/>
            </div>
        },
        itemRender() {
            const projectId = this.state.detailData.projectId;
            return (
                <div className="bottom-form">
                    {this.state.isFeedback ?
                        <textarea placeholder="反馈内容(必填) 限150字" name="result" id="result"></textarea> :
                        projectId ?
                            <PersonSelect addClass="no-department" type="auditor" projectId={projectId}/> :
                            ''
                    }
                </div>
            )
        },
        showFeedback() {
            this.setState({
                formVisible: 'this',
                formConVisible: 'this',
                isFeedback: true,
            });
        },
        showDispatch() {
            this.setState({
                formVisible: 'this',
                formConVisible: 'this',
                isFeedback: false,
            });
        },
        hideBottomForm() {
            this.setState({
                formVisible: '',
                formConVisible: '',
            });
        },

        submit() {
            var me = this,
              //  method = api.report.dispatch,
                $form = $('form'),
                appointmentTime = $form.find('#appointmentTime').val() + ':00',//后台需要加秒来转换为date类型
                location = $form.find('#location').val(),
                content = $form.find('#content').val(),
                $result,
                nextAccepterId;

            //时间非必填
            //if(!appointmentTime) {
            //    appAlert('请选择时间');
            //    return;
            //}

            if (!content || !location) {
                appAlert('请填写内容描述或工作位置');
                return;
            }

            if (this.state.isFeedback) {
                method = apiUrl +  '/api/work/event/updateEventReportByOrder';///api.dispatch;//api.report.feedback;
                $result = $('#result');
                if (!$result.val()) {
                    appAlert('请填写反馈结果');
                    return;
                }
            } else {
                nextAccepterId = $('.text-dot .choose').data('id');
                if (!nextAccepterId) {
                    alert('请选择下一步处理人');
                    return;
                }
            }

            ajax({
                url: method,//apiUrl + api.dispatch,
                type: 'POST',
                beforeSend() {
                    me.hideBottomForm();
                },
                headers: {
                    openId: dataId.openId,
                },
                data: {
                    eventId: eventId,
                    accepterId: this.props.user.id, //自己//员工ID？
                    nextAccepterId: nextAccepterId, //派单需要
                    //公共参数, 必填
                    appointmentTime: appointmentTime,
                    location: location,
                    content: content,
                    result: $result && $result.val(),

                    category: $form.find('#category').val(), //具体类别
                    eventType: $form.find('#eventType').val(), //
                    important: $form.find('#important').data('value') || 0, //重要【0:不重要，1:重要】
                    emergency: $form.find('#emergency').data('value') || 0, //紧急【0:不紧急，1:紧急】
                    serviceType: $form.find('#serviceType').data('value') || 0, //是否有偿
                    eventProcessResult: '', //内容补充描述,与产品商量后砍掉
                },
                success: function (data) {
                    $('.mui-bar').hide();

                    if (data.code == 'EVENTREPORT_ALREADY_PROCESSED') {
                        alert(data.desc, function () {
                            lf.bridgeJs.doClose();
                        })
                    } else {
                        alert('处理成功', function () {
                            lf.bridgeJs.doClose();
                        });
                    }
                }
            });
        },
        _enlargeHandler(imgSrc) {
            this.setState({
                imgSrc: imgSrc,
                largeImgVisible: 'this'
            });
        },
        _hideHandler() {
            this.setState({
                largeImgVisible: ''
            });
        }

    });

    lf.bridgeJs.getUser(function (user) {
        console.log(user)
        setTitle('处理详情');
        ajax({
            url: apiUrl + api.getGlobalId,
            type: 'post',
            data: {
                custGlobalId: user.globalId||user.custLoginVo.globalId,//user.id,'C1606281657108af41b8e068927' ||
            },

            success: function (data) {
                dataId=data.data;
                React.render(
                    <Root user={user}/>,
                    document.getElementById('root'), function () {
                        //$('#root').css({backgroundColor: '#efeff4'});
                    }
                );
             }
        })
    });
}

